import jwt from 'jsonwebtoken'

// token密钥
const tokenSecretKey = 'xwzs'
// 短token过期时间
const accessTokenMaxage = 30
// 长token过期时间
const refreshTokenMaxage = 60 * 60
// 创建短token
export const createAccessToken = (userInfo) => {
  return jwt.sign(userInfo, tokenSecretKey, { expiresIn: accessTokenMaxage })
}
// 创建长token
export const createRefreshToken = (userInfo) => {
  return jwt.sign(userInfo, tokenSecretKey, { expiresIn: refreshTokenMaxage })
}
// 校验token
export const verifyAccessToken = (token) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, tokenSecretKey, (error, decoded) => {
      if (error) {
        // console.log('');
        reject(error)
      }
      resolve(decoded)
    })
  })
}
// 校验刷新/长token
export const verifyRefreshToken = (token) => {
  console.log('token~~~', token)
  return new Promise((resolve, reject) => {
    jwt.verify(token, tokenSecretKey, (error, decoded) => {
      if (error) {
        console.log('在这？')
        reject(error)
      }

      resolve(decoded)
    })
  })
}

// 校验token 中间件
// verifyWhiteList 校验白名单
const verifyWhiteList = ['/v1/login', '/v1/refresh']
export const verifyTokenMiddleware = (req, res, next) => {
  // console.log('verifyTokenMiddleware222', req.path, req.url)
  console.log('req.method', req.method, 'baseURl:' + req.baseUrl, 'path:' + req.path)
  // 白名单和预检请求无需token, 可放行
  if (verifyWhiteList.includes(req.path) || req.method === 'OPTIONS') {
    next()
  } else {
    let authorization = ''
    const type = req.query?.type
    console.log('type', type)
    if (type === 'jsonp') {
      authorization = req.query?.tk
    } else {
      authorization = req.headers['authorization'] || req.headers['Authorization']
    }
    const token = authorization?.split('Bearer ')[1]
    console.log('req.headers', req.headers)
    if (!authorization) {
      return res.status(401).send({
        auth: false,
        message: 'No token',
      })
    }
    verifyAccessToken(token)
      .then((decoded) => {
        req.userId = decoded.userId
        next()
      })
      .catch((error) => {
        // token过期或token未通过
        console.log('error', JSON.stringify(error))
        // {"name":"JsonWebTokenError","message":"invalid token"}
        // {"name":"TokenExpiredError","message":"jwt expired","expiredAt":"2024-06-04T04:32:52.000Z"}
        return res.status(403).json({
          code: 403,
          message: error?.message,
        })
      })
  }
}

// export const tokenErrorMiddle = (err, req, res, next) => {
//   console.log('err', err)
// }
